from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.db.models import Sum, Count

from .models import LearningProgress, LearningHistory
from .serializers import LearningProgressSerializer, LearningHistorySerializer, UpdateProgressSerializer, LearningStatisticsSerializer
from user_app.utils import verify_token
from user_app.models import User

class LearningProgressView(APIView):
    @swagger_auto_schema(
        operation_summary="获取用户的学习进度列表",
        operation_description="获取当前登录用户的所有学习进度记录",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            ),
            openapi.Parameter(
                'content_type', openapi.IN_QUERY,
                description="可选，过滤内容类型（subject, content, question, chapter）",
                type=openapi.TYPE_STRING
            )
        ],
        responses={
            200: openapi.Response(
                description="获取学习进度列表成功",
                schema=LearningProgressSerializer(many=True)
            ),
            401: openapi.Response(description="未授权，请提供有效的token")
        }
    )
    def get(self, request):
        # 验证token
        token_data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not token_data or ('expired' in token_data and token_data['expired']):
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_id = token_data['id']
        
        # 过滤条件
        content_type = request.query_params.get('content_type')
        
        # 查询学习进度
        if content_type:
            progresses = LearningProgress.objects.filter(user_id=user_id, content_type=content_type)
        else:
            progresses = LearningProgress.objects.filter(user_id=user_id)
        
        serializer = LearningProgressSerializer(progresses, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    @swagger_auto_schema(
        operation_summary="创建或更新学习进度",
        operation_description="创建或更新用户对特定内容的学习进度",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            )
        ],
        request_body=LearningProgressSerializer,
        responses={
            200: openapi.Response(
                description="学习进度更新成功",
                schema=LearningProgressSerializer
            ),
            400: openapi.Response(description="参数错误")
        }
    )
    def post(self, request):
        # 验证token
        token_data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not token_data or ('expired' in token_data and token_data['expired']):
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_id = token_data['id']
        
        # 检查必要参数
        content_type = request.data.get('content_type')
        content_id = request.data.get('content_id')
        
        if not content_type or not content_id:
            return Response({"message": "缺少必要参数content_type或content_id"}, status=status.HTTP_400_BAD_REQUEST)
        
        # 查找或创建学习进度记录
        progress, created = LearningProgress.objects.get_or_create(
            user_id=user_id,
            content_type=content_type,
            content_id=content_id,
            defaults={
                'progress_percentage': request.data.get('progress_percentage', 0),
                'is_completed': request.data.get('is_completed', False),
                'learning_time_seconds': request.data.get('learning_time_seconds', 0)
            }
        )
        
        # 如果已存在，则更新进度
        if not created:
            serializer = UpdateProgressSerializer(progress, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
        serializer = LearningProgressSerializer(progress)
        return Response(serializer.data, status=status.HTTP_200_OK)

class ContentProgressView(APIView):
    @swagger_auto_schema(
        operation_summary="获取特定内容的学习进度",
        operation_description="根据内容类型和ID获取用户对特定内容的学习进度",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            ),
            openapi.Parameter(
                'content_type', openapi.IN_QUERY,
                description="内容类型（subject, content, question, chapter）",
                type=openapi.TYPE_STRING,
                required=True
            ),
            openapi.Parameter(
                'content_id', openapi.IN_QUERY,
                description="内容ID",
                type=openapi.TYPE_INTEGER,
                required=True
            )
        ],
        responses={
            200: openapi.Response(
                description="获取学习进度成功",
                schema=LearningProgressSerializer
            ),
            401: openapi.Response(description="未授权，请提供有效的token"),
            404: openapi.Response(description="未找到该内容的学习进度")
        }
    )
    def get(self, request):
        # 验证token
        token_data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not token_data or ('expired' in token_data and token_data['expired']):
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_id = token_data['id']
        content_type = request.query_params.get('content_type')
        content_id = request.query_params.get('content_id')
        
        if not content_type or not content_id:
            return Response({"message": "缺少必要参数content_type或content_id"}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            progress = LearningProgress.objects.get(
                user_id=user_id,
                content_type=content_type,
                content_id=content_id
            )
            serializer = LearningProgressSerializer(progress)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except LearningProgress.DoesNotExist:
            return Response({"message": "未找到该内容的学习进度"}, status=status.HTTP_404_NOT_FOUND)

class LearningHistoryView(APIView):
    @swagger_auto_schema(
        operation_summary="记录学习历史",
        operation_description="记录用户的学习历史记录",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            )
        ],
        request_body=LearningHistorySerializer,
        responses={
            201: openapi.Response(
                description="学习历史记录成功",
                schema=LearningHistorySerializer
            ),
            400: openapi.Response(description="参数错误")
        }
    )
    def post(self, request):
        # 验证token
        token_data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not token_data or ('expired' in token_data and token_data['expired']):
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_id = token_data['id']
        
        # 检查必要参数
        content_type = request.data.get('content_type')
        content_id = request.data.get('content_id')
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        
        if not content_type or not content_id or not start_time or not end_time:
            return Response({"message": "缺少必要参数"}, status=status.HTTP_400_BAD_REQUEST)
        
        # 计算学习时长
        from datetime import datetime
        start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
        end_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
        duration_seconds = int((end_dt - start_dt).total_seconds())
        
        # 创建学习历史记录
        history = LearningHistory.objects.create(
            user_id=user_id,
            content_type=content_type,
            content_id=content_id,
            start_time=start_time,
            end_time=end_time,
            duration_seconds=duration_seconds
        )
        
        # 同时更新学习进度中的学习时长
        try:
            progress = LearningProgress.objects.get(
                user_id=user_id,
                content_type=content_type,
                content_id=content_id
            )
            progress.learning_time_seconds += duration_seconds
            progress.save()
        except LearningProgress.DoesNotExist:
            # 如果进度记录不存在，也不影响历史记录的创建
            pass
        
        serializer = LearningHistorySerializer(history)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

class LearningStatisticsView(APIView):
    @swagger_auto_schema(
        operation_summary="获取学习统计信息",
        operation_description="获取用户的学习统计数据",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            ),
            openapi.Parameter(
                'content_type', openapi.IN_QUERY,
                description="可选，过滤内容类型（subject, content, question, chapter）",
                type=openapi.TYPE_STRING
            )
        ],
        responses={
            200: openapi.Response(
                description="获取学习统计信息成功",
                schema=LearningStatisticsSerializer
            ),
            401: openapi.Response(description="未授权，请提供有效的token")
        }
    )
    def get(self, request):
        # 验证token
        token_data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not token_data or ('expired' in token_data and token_data['expired']):
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_id = token_data['id']
        content_type = request.query_params.get('content_type')
        
        # 查询条件
        if content_type:
            progresses = LearningProgress.objects.filter(user_id=user_id, content_type=content_type)
        else:
            progresses = LearningProgress.objects.filter(user_id=user_id)
        
        # 计算统计数据
        total_learning_time = progresses.aggregate(Sum('learning_time_seconds'))['learning_time_seconds__sum'] or 0
        completed_items = progresses.filter(is_completed=True).count()
        total_items = progresses.count()
        progress_rate = (completed_items / total_items) * 100 if total_items > 0 else 0
        
        # 返回统计数据
        statistics = {
            'total_learning_time_seconds': total_learning_time,
            'completed_items': completed_items,
            'total_items': total_items,
            'progress_rate': progress_rate
        }
        
        serializer = LearningStatisticsSerializer(statistics)
        return Response(serializer.data, status=status.HTTP_200_OK)
